document.addEventListener('DOMContentLoaded', () => {
    const gridDisplay = document.querySelector('#game-container');
    let squares = [];

    function createBoard() {
        for (let i = 0; i < 16; i++) {
            let square = document.createElement('div');
            square.innerHTML = 0;
            square.classList.add('tile');
            gridDisplay.appendChild(square);
            squares.push(square);
        }
        generate();
        generate();
    }

    // 确保generate函数能够运行并在随机方块中设置数字
    function generate() {
        let randomNumber = Math.floor(Math.random() * squares.length);
        if (squares[randomNumber].innerHTML == 0) {
            squares[randomNumber].innerHTML = 2;
        } else generate();
    }

    createBoard();
});

document.addEventListener('keydown', control);

function control(e) {
    if(e.keyCode === 37) {
        keyLeft();
    } else if(e.keyCode === 38) {
        keyUp();
    } else if(e.keyCode === 39) {
        keyRight();
    } else if(e.keyCode === 40) {
        keyDown();
    }
}

function keyLeft() {
    // 左移逻辑
    combineRow();
    console.log('Moved Left');
    // 此处应添加移动方格的代码
}

function keyRight() {
    // 右移逻辑
    combineRow();
    console.log('Moved Right');
    // 此处应添加移动方格的代码
}

function keyUp() {
    // 上移逻辑
    combineRow();
    generate();
    console.log('Moved Up');
    // 此处应添加移动方格的代码
}

function keyDown() {
    // 下移逻辑
    combineRow();
    generate();
    console.log('Moved Down');
    // 此处应添加移动方格的代码
}

function combineRow() {
    for (let i = 0; i < 15; i++) {
        if (squares[i].textContent === squares[i + 1].textContent) {
            let combinedTotal = parseInt(squares[i].textContent) + parseInt(squares[i + 1].textContent);
            squares[i].textContent = combinedTotal;
            squares[i + 1].textContent = '';
            // 更新分数或其他游戏状态
        }
    }
    checkForWin();
}


// 检查游戏是否胜利
function checkForWin() {
    for (let i = 0; i < squares.length; i++) {
        if (squares[i].textContent == '2048') {
            // 游戏胜利逻辑，例如显示胜利消息
            console.log('You win!');
        }
    }
}